package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.pojo.tanhua.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UsersApi;
import com.tanhua.dubbo.pojo.Comment;
import com.tanhua.dubbo.pojo.Users;
import com.tanhua.server.vo.Contacts;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private AnnouncementService announcementService;

    @Value("${tanhua.sso.url}")
    private String url;


    /**
     * 添加好友
     *
     * @param userId 好友id
     * @return
     */
    public boolean contactUser(Long userId) {
        /*
            1. 保存到mongodb
            2. 注册到环信
         */
        User user = UserThreadLocal.get();

        Users users = new Users();
        users.setUserId(user.getId());
        users.setFriendId(userId);

        String id = this.usersApi.saveUsers(users);
        if (StringUtils.isNotEmpty(id)) {
            //注册好友关系到环信
            String targetUrl = url + "/user/huanxin/contacts/" + users.getUserId() + "/" + users.getFriendId();
            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, null, Void.class);
            return responseEntity.getStatusCodeValue() == 200;
        }
        return false;
    }

    /**
     * 查看好友列表
     *
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResult queryFriendList(Integer page, Integer pageSize, String keyword) {
        User user = UserThreadLocal.get();

        List<Users> usersList;
        if (StringUtils.isNotEmpty(keyword)) {
            //关键不为空，查询所有的好友，在后面进行关键字过滤
            usersList = usersApi.queryAllUsersList(user.getId());
        } else {
            //关键字为空，进行分页查询
            PageInfo<Users> pageInfo = usersApi.queryUsersList(user.getId(), page, pageSize);
            usersList = pageInfo.getRecords();
        }

        // 封住好友的id
        List<Long> userIds = new ArrayList<>();
        for (Users users : usersList) {
            userIds.add(users.getFriendId());
        }

        // 构造查询条件，查询用户的信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        // 如果keyword不为空，根据keyword进行模糊查询
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("nick_name", keyword);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<UserInfo> userInfoList = userInfoService.queryList(queryWrapper);
        if (userInfoList == null){
            return pageResult;
        }

        // 封装好友的信息Contacts对象
        List<Contacts> contactsList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            Contacts contacts = new Contacts();
            contacts.setAge(userInfo.getAge());
            contacts.setAvatar(userInfo.getLogo());
            contacts.setGender(userInfo.getSex().name().toLowerCase());
            contacts.setNickname(userInfo.getNickName());
            contacts.setUserId(String.valueOf(userInfo.getUserId()));
            contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            contactsList.add(contacts);
        }

        pageResult.setItems(contactsList);

        return pageResult;
    }

    /**
     * 接收到点赞的列表
     *
     * @param page 当前页
     * @param pageSize 每页显示的大小
     * @return 点赞人的信息列表
     */
    public PageResult queryUserLikeList(Integer page, Integer pageSize){
        return queryCommentList(page,pageSize,1);
    }

    /**
     * 接收到评论的列表
     *
     * @param page 当前页
     * @param pageSize 每页显示的大小
     * @return 点赞人的信息列表
     */
    public PageResult queryUserCommentList(Integer page, Integer pageSize){
        return queryCommentList(page,pageSize,2);
    }

    /**
     * 接收到喜欢的列表
     *
     * @param page 当前页
     * @param pageSize 每页显示的大小
     * @return 点赞人的信息列表
     */
    public PageResult queryUserLoveList(Integer page, Integer pageSize){
        return queryCommentList(page,pageSize,3);
    }

    /**
     * 查询公告列表
     *
     * @param page 当前页数
     * @param pageSize 每页的大小
     * @return 公告列表
     */
    public PageResult queryAnnouncementsList(Integer page, Integer pageSize) {
        // 构建PageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        // 获取封装公告信息的列表，如果为空，则直接返回PageResult对象
        IPage<Announcement> announcementIPage = announcementService.queryAnnouncementList(page, pageSize);
        List<Announcement> records = announcementIPage.getRecords();
        if (records.size() == 0){
            return pageResult;
        }

        // 循环遍历List<Announcement> records，并对MessageAnnouncement对象进行封装
        List<MessageAnnouncement> messageAnnouncementList = new ArrayList<>();
        for (Announcement record : records) {
            MessageAnnouncement messageAnnouncement = new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncement.setDescription(record.getDescription());
            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

            messageAnnouncementList.add(messageAnnouncement);
        }

        pageResult.setItems(messageAnnouncementList);
        return pageResult;
    }

    /**
     * 查询用户点赞，喜欢，评论的列表
     *
     * @param page 当前页
     * @param pageSize 每页显示的大小
     * @param type 评论的类型：1 点赞； 2 评论； 3 喜欢
     * @return 评论人的信息列表
     */
    private PageResult queryCommentList(Integer page, Integer pageSize,Integer type) {
        User user = UserThreadLocal.get();
        // 封装PageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        // 获取有关点赞的信息
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentListByUser(user.getId(), type, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (records == null){
            return pageResult;
        }

        // 封装userId作为查询条件
        List<Long> ids = new ArrayList<>();
        for (Comment record : records) {
            ids.add(record.getUserId());
        }

        if (ids.size() == 0) {
            return pageResult;
        }

        // 构造查询条件
        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",ids);
        List<UserInfo> userInfoList = userInfoService.queryList(query);

        List<MessageLike> messageLikeList = new ArrayList<>();
        // 遍历列表，封装messageLikeList对象
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()){
                    MessageLike messageLike = new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setCreateDate(String.valueOf(System.currentTimeMillis()));
                    messageLikeList.add(messageLike);
                    break;
                }
            }
        }

        pageResult.setItems(messageLikeList);
        return pageResult;
    }
}
